package org.apache.skywalking.apm.plugin.spring.mvc.commons.define;

import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine;
import org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;
import org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;

import static net.bytebuddy.matcher.ElementMatchers.named;

/**
 * 拦截springmvc请求分发器
 */
public class DispatcherServletInterceptorPlugin extends ClassInstanceMethodsEnhancePluginDefine {

    private static final String DISPATCHER_SERVLET_CLASS = "org.springframework.web.servlet.DispatcherServlet";
    public static final String ORG_APACHE_SKYWALKING_APM_PLUGIN_SPRING_MVC_V_4_DISPATCHER_SERVLET_INTERCEPTOR = "org.apache.skywalking.apm.plugin.spring.mvc.commons.interceptor.DispatcherServletInterceptor";
    public static final String PROCESS_DISPATCH_RESULT = "processDispatchResult";

    @Override
    public ClassMatch enhanceClass() {
        return NameMatch.byName(DISPATCHER_SERVLET_CLASS);
    }

    @Override
    public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
        return null;
    }

    @Override
    public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
        return new InstanceMethodsInterceptPoint[]{
                new InstanceMethodsInterceptPoint() {
                    @Override
                    public ElementMatcher<MethodDescription> getMethodsMatcher() {
                        return named(PROCESS_DISPATCH_RESULT);
                    }

                    @Override
                    public String getMethodsInterceptor() {
                        return ORG_APACHE_SKYWALKING_APM_PLUGIN_SPRING_MVC_V_4_DISPATCHER_SERVLET_INTERCEPTOR;
                    }

                    @Override
                    public boolean isOverrideArgs() {
                        return false;
                    }
                }
        };
    }
}